import os
import uuid

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, mixins

from Django_template import settings
from user.models import BookUserMode

from rest_framework_simplejwt.exceptions import InvalidToken
from rest_framework_simplejwt.views import TokenObtainPairView
from serializer import UserSerializer
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.generics import GenericAPIView, get_object_or_404, CreateAPIView, RetrieveAPIView, \
    ListCreateAPIView, RetrieveUpdateAPIView,ListAPIView

from serializer.UserSerializer import UserInfoSerializer
from common.pagination import MyPageNumberPagination

class LoginView(TokenObtainPairView, BaseException):

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        try:
            serializer.is_valid(raise_exception=True)
        except Exception as e:
            return Response({'code': 0, 'msg': '账号或密码错误'},
                            status=status.HTTP_200_OK)
        # 自定义登陆成功之后的结果
        result = serializer.validated_data
        result['id'] = serializer.user.id
        result['username'] = serializer.user.username
        result['token'] = result.pop('access')
        return Response(serializer.validated_data, status=status.HTTP_200_OK)


class RegiserView(APIView):
    permission_classes = []

    def post(self, request):
        print(request.data)
        username = request.data.get('username')
        password = request.data.get('password')
        password_confirmation = request.data.get('password_confirmation')
        issuper = request.data.get('issuper')
        if BookUserMode.objects.filter(username=username).exists():
            return Response({'error': '用户名已被注册'}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
        if not all([username, password, password_confirmation]):
            return Response({'error': '所有参数不能为空'}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
        # 校验两次密码是否一致
        if password != password_confirmation:
            return Response({'error': '两次密码不一致'}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
        if issuper == 'liz':
            obj = BookUserMode.objects.create_superuser(username=username, password=password)
        else:
            obj = BookUserMode.objects.create_user(username=username, password=password)
        res = {
            "username": obj.username,
            "id": obj.id,
            "msg": "注册成功"
        }
        return Response(res, status=status.HTTP_201_CREATED)




class ChangeUserView(GenericAPIView):
    permission_classes = [IsAuthenticated]
    queryset = BookUserMode.objects.all()
    serializer_class = UserInfoSerializer

    def get_permissions(self):
        # 如果是创建(get)方法，添加AllowAny权限
        if self.request.method == 'GET':
            return [AllowAny()]
        # 对于其他方法，使用全局权限类
        return super().get_permissions()

    def get(self,request):
        try:
            userid = request.user.id
            userdict = BookUserMode.objects.get(id=userid)
            serializer = self.get_serializer(userdict)
            if serializer:
                return Response(serializer.data)
        except Exception as e:
            return Response({'code':0, 'message': '未登录或其他错误'}, status=status.HTTP_200_OK)

    def put(self, request, *args, **kwargs):
        try:
            userid = request.user.id
            userdict = BookUserMode.objects.get(id=userid)
            serializer = self.get_serializer(userdict, data=request.data, partial=True)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            return Response(serializer.data)
        except Exception as e:
            return Response({"message": str(e),'code':0}, status=200)

